<?php
    session_start();
    //处理当前用户
    $user = isset($_SESSION["user"])?$_SESSION["user"]:null;
    $userId = $user?$user["Id"]:null;
    
    // $theme = isset($_GET["theme"])?$_GET["theme"]:null;
    // if(!$theme){
    //     $theme = isset($_COOKIE["theme"])?$_COOKIE["theme"]:null;
    // }else{
    //     setcookie("theme",$theme);
    // }
    // if(!$theme) $theme = "default";

    //处理数据库
    function createDb(){
        return new mysqli("localhost","root","root","myblog");
    }

    
    function pageURL($pageIndex){
        $pageString = "pageIndex=$pageIndex";
        foreach ($_GET as $k => $v) {
            if($k==="pageIndex") continue;
            $pageString .="&$k=$v";
        }
        return $pageString;
    }

    
function getParam($name){
    $value = isset($_GET[$name])?trim($_GET[$name]):"";
    $value = str_replace("'","''",$value);
    return $value;
}

function pageable($tbname,$where,$order,$pageIndex,$pageSize){
    
    $start = ($pageIndex-1)*$pageSize;
    $conn = createDb();
    $itemsSql = "select *  from  `$tbname`";
    if($where) $itemsSql.=" where ".$where;
    if($order) $itemsSql.=" order by ".$order;
    $itemsSql.=" limit $start,$pageSize";
    $rs = $conn->query($itemsSql);
    $items = [];
    while($record = $rs->fetch_assoc()) $items[] = $record;
    $rs->close();

    $countSql = "select count(*) as c from `$tbname`";
    if($where) $countSql .= " where ".$where;
    $rs = $conn->query($countSql);
    $total = $rs->fetch_assoc()["c"];
    $rs->close();
    $pageCount = ceil($total/$pageSize);
    return[
        "items"=>$items,
        "total"=>$total,
        "pageCount"=>$pageCount
    ];
}
?>